package Client;

import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.io.*;
import java.net.*;
/**
 * Client
 * 
 * @author Yaxing Chen
 *
 */
public class Client {
	
	private JFrame jf;
	private JTextField field;
	private Cursor cursor;
	private JTextArea area;
	private JButton button;
	private JButton clear;
	private Panel panel;
	private Dimension d;
	private Toolkit toolkit;
	
	private int clientId;
	
	private void startClient(){
        
        try{
            Socket s = new Socket("127.0.0.1",2008);
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();
            DataInputStream dis = new DataInputStream(is);
            DataOutputStream dos = new DataOutputStream(os);
            
            
           // retrieve user ID from 
            dos.writeUTF("__ID");
            String getId = dis.readUTF();
            clientId = Integer.parseInt(getId);
            
            createUI();
            
            ClientSender say = new ClientSender(dos,field,button,area,clear);
            ClientReceiver receiver = new ClientReceiver(dis, area, 1, clientId);               
            button.addActionListener(say);
            clear.addActionListener(say);
            field.addKeyListener(say);
            jf.addFocusListener(say);
            
            receiver.start();
            
        }catch(IOException e){
            e.printStackTrace();
        }
	}
	
	private void createUI(){
		jf = new JFrame("Client " + clientId);
        field = new JTextField(30);
        cursor = new Cursor(Cursor.TEXT_CURSOR);
        field.requestFocusInWindow();
        area = new JTextArea();
        area.setEditable(false);
        area.setFont(new Font("Times New Roman",0,14));
        button = new JButton("Send");
        clear = new JButton("Clear");
        panel = new Panel();
        panel.add(field);
        panel.add(button);
        panel.add(clear);
        jf.add(area,"Center");
        jf.add(panel,"South");
        toolkit = jf.getToolkit();
        d = toolkit.getScreenSize();
        jf.setBounds(d.width/2-268,d.height/2-163,536,327);
        jf.setResizable(false);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.validate();
	}
	
    public static void main(String args[]){
       Client client = new Client();
       client.startClient();
    }
}
